package com.bigknow.appstore.server.common;

import com.bigknow.appstore.common.AppStoreRuntimeException;
import com.bigknow.appstore.common.inf.HandlerInterface;
import com.bigknow.appstore.common.inf.server.common.FileStoreHandler;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
import org.apache.commons.io.IOUtils;
import org.mongodb.morphia.Datastore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Base64;

/**
 * Created by 李科风 on 2015/12/9.
 */
@Service
@HandlerInterface(FileStoreHandler.class)
public class FileStoreHandlerImpl implements FileStoreHandler {

    @Autowired
    private Datastore ds;

    @Override
    public void addFile(String fileName, String data) {
        GridFS fs = new GridFS(ds.getDB());
        GridFSDBFile oldFile = fs.findOne(fileName);
        if (oldFile != null) {
            throw new AppStoreRuntimeException(String.format("文件(%s)已存在", fileName));
        }
        GridFSInputFile file = fs.createFile(Base64.getDecoder().decode(data));
        file.setFilename(fileName);
        file.save();
    }

    @Override
    public boolean exists(String fileName) {
        GridFS fs = new GridFS(ds.getDB());
        return fs.findOne(fileName) != null;
    }

    @Override
    public String getFile(String fileName) {
        GridFS fs = new GridFS(ds.getDB());
        GridFSDBFile file = fs.findOne(fileName);
        try {
            byte[] buf = IOUtils.toByteArray(file.getInputStream());
            return Base64.getEncoder().encodeToString(buf);
        } catch (IOException e) {
            throw new AppStoreRuntimeException(String.format("读取文件(%s)失败", fileName), e);
        }
    }

    @Override
    public void updateFile(String fileName, String data) {
        if (!exists(fileName)) {
            throw new AppStoreRuntimeException(String.format("文件(%s)不存在", fileName));
        }
        removeFile(fileName);
        addFile(fileName, data);
    }

    @Override
    public void removeFile(String fileName) {
        GridFS fs = new GridFS(ds.getDB());
        fs.remove(fileName);
    }
}
